<template>
  <el-container class="main-container">
    <!-- 外层垂直滑动容器 -->
    <swiper
      ref="verticalSwiper"
      :options="verticalSwiperOptions"
      @slideChange="handleVerticalSlideChange"
      class="vertical-swiper"
    >
      <swiper-slide v-for="(item, vIndex) in imgList" :key="`vertical_${vIndex}`" class="vertical-slide">
        <!-- 多张图片逻辑 -->
        <template>
          <swiper
            :ref="`horizontalSwiper_${vIndex}`"
            :options="horizontalSwiperOptions"
            @slideChange="swiper => handleHorizontalSlideChange(vIndex)"
            class="horizontal-swiper"
            @init="swiper => handleHorizontalInit(vIndex, swiper)"
          >
            <swiper-slide
              v-for="(img, hIndex) in item.images"
              :key="`horizontal_${vIndex}_${hIndex}`"
              class="horizontal-slide"
            >
              <div class="image-container">
                <img
                  :src="img.url"
                  alt="作品图片"
                  class="full-image"
                  :class="{ loaded: img.loaded }"
                  @load="img.loaded = true"
                  draggable="false"
                />
              </div>
            </swiper-slide>
          </swiper>
          <!-- 水平指示器（修复同步问题） -->
          <div class="horizontal-dots">
            <span
              v-for="(img, hIndex) in item.images"
              :key="`dot_${vIndex}_${hIndex}`"
              :class="{ active: currentHorizontalIndexes[vIndex] === hIndex }"
              class="dot"
              @click="setHorizontalIndex(vIndex, hIndex)"
            ></span>
          </div>
        </template>

        <!-- 左下角信息 -->
        <div class="left-info">
          <div class="leftbox">
            <div class="title">{{ getTitle(item) }}</div>
            <div class="time">{{ item.created_at }}</div>
          </div>
          <div class="lsftbtm">
            <div class="lock-icon" v-if="item.locked">🔒</div>
            <el-button type="primary" size="mini" class="draw-btn">画同款</el-button>
          </div>
        </div>

        <!-- 右侧操作栏 -->
        <div class="right-actions">
          <el-avatar :size="40" :src="getAvatar(item)" class="avatar" />
          <div class="action-item" @click="handleLike(item, vIndex)">
            <img v-if="item.is_like === 0" class="collect" src="@/assets/images/like-fff.png" alt="" />
            <img v-else class="collect" src="@/assets/images/like-red.png" alt="" />
            <span class="count">{{ item.likes || 0 }}</span>
          </div>
          <div class="action-item" @click="openCommentDialog(vIndex)">
            <img class="collect" src="@/assets/images/comment-icon.png" alt="" />

            <span class="count">{{ item.comments || 0 }}</span>
          </div>
          <div class="action-item" @click="handleCollect(item)">
            <img v-if="item.is_favorite === 0" class="collect" src="@/assets/images/collect-icon.png" alt="" />
            <img v-else class="collect" src="@/assets/images/collectd-icon.png" alt="" />

            <span class="count">{{ item.favorite_count || 0 }}</span>
          </div>

          <div class="action-item" @click="handleShare(item)">
            <img class="collect" src="@/assets/images/share-icon.png" alt="" />

            <span class="count">{{ item.shares || 0 }}</span>
          </div>
        </div>
      </swiper-slide>
    </swiper>
    <CommentDialog
      :visible.sync="commentVisible"
      :work-id="currentCommentWorkId"
      :comment-count="currentCommentCount"
      @clickAuthor="handleReplyAuthor"
      @update:commentCount="
        newCount => {
          currentCommentCount = newCount
          // 找到当前评论的作品在 imgList 中的索引
          const workIndex = imgList.findIndex(item => item.work_id === currentCommentWorkId)
          if (workIndex !== -1) {
            // 同步更新该作品的评论数
            this.$set(imgList[workIndex], 'comments', newCount)
          }
        }
      "
    />
    <!-- 评论对话框 -->
    <!-- <el-dialog title="评论" :visible.sync="dialogVisible" width="30%" @close="resetComment">
      <p>当前展示的作品：{{ currentItem.title || '未命名作品' }}</p>
      <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="commentText" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交</el-button>
      </div>
    </el-dialog> -->
  </el-container>
</template>

<script>
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/css/swiper.min.css'
import { getRecommendList, getpublicList, getfavorite, getfollow, workLike, workfavorite } from '@/api/workserve'
import { getToken } from '@/utils/auth'
// 引入评论子组件
import CommentDialog from './CommentDialog.vue'
export default {
  components: {
    swiper: VueAwesomeSwiper.swiper,
    swiperSlide: VueAwesomeSwiper.swiperSlide,
    CommentDialog,
  },
  props: {
    // 接收父组件传递的 activeTab
    activeTab: {
      type: String,
      default: 'recommend', // recommend, favorites, follow
    },
  },
  data() {
    return {
      imgList: [],
      currentVerticalIndex: 0,
      currentHorizontalIndexes: [], // 存储每个垂直项的当前水平索引
      horizontalSwipers: [],
      refreshDistance: 0,
      startY: 0,
      isRefreshing: false,
      pages: {
        cursor: 0,
        limit: 20,
      },
      isLoadingMore: false,
      isflag: false,
      noMoreData: false,
      hasLoadedOnce: false, // 标记是否已加载过一次数据（解决默认显示问题）
      dialogVisible: false,
      currentItem: {},
      commentText: '',
      commentVisible: false, // 评论弹窗显示状态
      currentCommentWorkId: '', // 当前评论的作品ID
      currentCommentCount: 0, // 当前评论数
      userInfo: localStorage.getItem('userinfo') || {}, // 当前用户信息（从vuex或接口获取）
    }
  },
  watch: {
    // 监听 activeTab 变化，当标签切换时重新加载数据
    activeTab: {
      immediate: true,
      handler(newTab, oldTab) {
        if (newTab !== oldTab) {
          console.log(`标签切换: ${oldTab} -> ${newTab}`)
          this.imgList = []
          this.reloadList()
        }
      },
    },
  },
  computed: {
    refreshTipText() {
      if (this.isRefreshing) return '刷新中...'
      return this.refreshDistance > 50 ? '松开刷新' : '下拉刷新（拖拽顶部）'
    },
    verticalSwiperOptions() {
      return {
        direction: 'vertical',
        slidesPerView: 1,
        spaceBetween: 0,
        mousewheel: true,
        loop: false,
        simulateTouch: true,
        preventInteractionOnTransition: false,
        observer: true,
        observeParents: true,
        slideToClickedSlide: true,
        on: {
          reachEnd: this.handleReachEnd,
        },
      }
    },
    horizontalSwiperOptions() {
      return {
        direction: 'horizontal',
        slidesPerView: 1,
        spaceBetween: 0,
        mousewheel: false,
        simulateTouch: true,
        preventInteractionOnTransition: true,
        observer: true,
        observeParents: true,
        grabCursor: true,
      }
    },
  },
  mounted() {
    window.addEventListener('mousedown', this.handleMouseDown)
    window.addEventListener('mousemove', this.handleMouseMove)
    window.addEventListener('mouseup', this.handleMouseUp)
  },
  beforeDestroy() {
    window.removeEventListener('mousedown', this.handleMouseDown)
    window.removeEventListener('mousemove', this.handleMouseMove)
    window.removeEventListener('mouseup', this.handleMouseUp)
  },
  methods: {
    // 初始化数据
    // / 初始化数据 - 按照小程序逻辑
    async reloadList() {
      this.pages = {
        cursor: 0,
        limit: 20,
      }
      this.isLoadingMore = false
      this.noMoreData = false
      this.items = []
      await this.init()
    },
    async init() {
      this.isLoadingMore = true
      try {
        const params = {
          ...this.pages,
        }
        let res = null
        if (getToken()) {
          if (this.activeTab === 'recommend') {
            res = await getRecommendList(params)
          } else if (this.activeTab === 'favorites') {
            res = await getfavorite(params)
          } else {
            res = await getfollow(params)
          }
        } else {
          res = await getpublicList(params)
        }
        const { items, next_cursor } = res.data
        if (items && items.length > 0) {
          const formattedItems = this.formatItems(items)
          // 如果是第一页，直接替换；否则追加
          if (this.pages.cursor === 0) {
            this.imgList = formattedItems
          } else {
            this.imgList = [...this.imgList, ...formattedItems]
          }
          console.log(next_cursor, '6666666666')
          console.log(this.imgList.length, '1111111111111111111')
          this.currentHorizontalIndexes = this.imgList.map(() => 0)
          // 更新分页游标
          this.pages.cursor = next_cursor || 0

          // 判断是否还有更多数据
          this.noMoreData = !next_cursor
          console.log('是否还有更多数据:', !this.noMoreData)
        } else {
          // 没有数据了
          this.noMoreData = true
          console.log('没有更多作品数据了')
        }
      } catch (error) {
        console.error('初始化数据失败：', error)
        this.hasLoadedOnce = true // 失败也标记，避免空白
      } finally {
        this.isLoadingMore = false
      }
    },
    // 打开评论弹窗
    openCommentDialog(vIndex) {
      if (!getToken()) {
        this.$message.warning('请先登录再操作！') // 改用 warning 提示更醒目
        return
      }
      const item = this.imgList[vIndex]
      this.currentCommentWorkId = item.work_id
      this.currentCommentCount = item.comments || 0
      this.commentVisible = true
    },

    // 点击评论作者头像跳转
    handleReplyAuthor(comment) {
      // this.$router.push({
      //   path: '/pagesA/personalInfo/index',
      //   query: {
      //     open_id: comment.open_id,
      //     is_follow: comment.is_follow,
      //     is_mutual: comment.is_mutual,
      //   },
      // })
    },
    // 数据格式化
    formatItems(items) {
      return items.map(item => ({
        ...item,
        // 映射字段，确保与模板中使用的一致
        images: item.images
          ? item.images.map(img => ({
              ...img,
              loaded: false,
              url: img.url || img, // 兼容不同格式
            }))
          : [
              {
                url: item.icon || item.cover,
                loaded: false,
              },
            ],
        likes: item.like_count || item.likes || 0,
        collects: item.collect_count || item.collects || 0,
        comments: item.comment_count || item.comments || 0,
        shares: item.share_count || item.shares || 0,
        created_at: item.create_time || item.created_at,
        title: item.title || '未命名作品',
        avatar: item.author_avatar || item.avatar,
      }))
    },
    // 数据请求
    async fetchData(cursor) {
      const param = { cursor, limit: this.limit }
      return await getRecommendList(param)
    },
    // 下拉刷新相关
    handleMouseDown(e) {
      if (this.$refs.verticalSwiper?.swiper && this.$refs.verticalSwiper.swiper.activeIndex === 0) {
        this.startY = e.clientY
      }
    },
    handleMouseMove(e) {
      if (this.startY === 0 || this.isRefreshing) return
      const moveY = e.clientY - this.startY
      if (moveY > 0) {
        this.refreshDistance = Math.min(moveY, 100)
      }
    },
    handleMouseUp() {
      if (this.refreshDistance > 50 && !this.isRefreshing) {
        this.doRefresh()
      } else {
        this.refreshDistance = 0
      }
      this.startY = 0
    },
    async doRefresh() {
      this.isRefreshing = true
      this.refreshDistance = 60
      try {
        await this.reloadList()
        if (this.$refs.verticalSwiper?.swiper) {
          this.$refs.verticalSwiper.swiper.slideTo(0)
        }
      } catch (error) {
        console.error('刷新失败：', error)
      } finally {
        this.isRefreshing = false
        this.refreshDistance = 0
      }
    },
    // 加载更多
    async loadMoreData() {
      if (this.isLoadingMore || this.noMoreData) {
        return
      }
      await this.init()
    },
    // 垂直滑动到底部触发加载更多
    async handleReachEnd() {
      if (this.isflag || this.isLoadingMore || this.noMoreData) {
        return
      }

      this.isflag = true
      try {
        await this.loadMoreData()
      } finally {
        this.isflag = false
      }
    },
    // 初始化水平swiper时强制同步索引

    // 滑动时同步索引（增加强制更新逻辑）
    handleHorizontalSlideChange(vIndex) {
      const swiperRef = this.$refs[`horizontalSwiper_${vIndex}`]
      if (!swiperRef || !swiperRef.length) return
      const swiper = swiperRef[0].swiper
      if (!swiper) return
      const currentHIndex = swiper.activeIndex
      this.$set(this.currentHorizontalIndexes, vIndex, currentHIndex)
      // 强制更新视图
      this.$forceUpdate()
    },
    // 垂直滑动切换
    handleVerticalSlideChange() {
      const verticalSwiper = this.$refs.verticalSwiper?.swiper
      this.currentVerticalIndex = verticalSwiper ? verticalSwiper.activeIndex : 0
      // this.currentVerticalIndex = this.$refs.verticalSwiper?.swiper?.activeIndex || 0
    },
    // 水平swiper初始化时同步索引（修复初始不同步）
    handleHorizontalInit(vIndex, swiper) {
      // 确保索引数组长度与垂直项匹配
      if (this.currentHorizontalIndexes.length <= vIndex) {
        this.currentHorizontalIndexes[vIndex] = 0
      } else {
        this.$set(this.currentHorizontalIndexes, vIndex, swiper.activeIndex)
      }
    },

    // 设置水平滑动索引
    setHorizontalIndex(vIndex, hIndex) {
      const swiperRef = this.$refs[`horizontalSwiper_${vIndex}`]
      // 确保ref存在且是数组格式，取第一个元素的swiper实例
      if (Array.isArray(swiperRef) && swiperRef.length > 0) {
        const swiper = swiperRef[0].swiper
        if (swiper && typeof swiper.slideTo === 'function') {
          swiper.slideTo(hIndex)
          this.$set(this.currentHorizontalIndexes, vIndex, hIndex)
        }
      }
    },
    resetComment() {
      this.commentText = ''
    },
    submitComment() {
      if (this.commentText.trim()) {
        this.$set(this.currentItem, 'comments', (this.currentItem.comments || 0) + 1)
        this.dialogVisible = false
        this.commentText = ''
      }
    },
    async handleUnlock(item) {
      this.selectWork = item || null
      if (item.prompt_hide_switch === 0 || item.is_unlock === 1) {
        this.$confirm('确认画同款？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(() => {
          this.submitUnlock()
        })
      } else {
        const { prompt_points, work_id } = this.selectWork
        this.$confirm(`需要消耗 ${prompt_points || 0} 个次元币，是否确认解锁？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(async () => {
          const { code, data, msg } = await this.COM_HTTP.workUnlock({
            work_id,
          })
          if (code === 200) {
            this.submitUnlock()
            item.is_unlock = 1
            this.setWorkPendingUpdates()
          } else if (code === 201) {
            this.insufficientPoints()
          }
        })
        // uni.showModal({
        //   title: '解锁画同款',
        //   content,
        //   cancelText: '取消',
        //   confirmText: '确认',
        //   confirmColor: '#e6262c',
        //   success: async res => {
        //     if (res.confirm) {
        //       const { code, data, msg } = await this.COM_HTTP.workUnlock({
        //         work_id,
        //       })
        //       if (code === 200) {
        //         this.submitUnlock()
        //         item.is_unlock = 1
        //         this.setWorkPendingUpdates()
        //       } else if (code === 201) {
        //         this.insufficientPoints()
        //       } else {
        //         uni.showToast({
        //           title: msg,
        //           icon: 'error',
        //         })
        //       }
        //     }
        //   },
        // })
      }
    },
    // 工具方法
    hasMultipleImages(item) {
      return item.images && item.images.length > 1
    },
    getTitle(item) {
      return item.title || '未命名作品'
    },
    getTime(item) {
      console.log(item, '99999999')
      return item.time || '未知时间'
    },
    getAvatar(item) {
      return item.avatar || 'https://picsum.photos/40/40'
    },

    // 点赞
    async handleLike(item, vIndex) {
      if (!getToken()) {
        this.$message.warning('请先登录再操作！') // 改用 warning 提示更醒目
        return
      }
      // const work = this.works[workIndex];
      console.log(item, 'item')
      const { code, data, msg } = await workLike({
        work_id: item.work_id,
      })
      if (code === 200) {
        item.is_like = item.is_like === 1 ? 0 : 1
        item.like_count += item.is_like ? 1 : -1
        // this.setWorkPendingUpdates()
      }
    },
    // 收藏
    async handleCollect(item) {
      if (!getToken()) {
        this.$message.warning('请先登录再操作！') // 改用 warning 提示更醒目
        return
      }
      const { code, data, msg } = await workfavorite({
        work_id: item.work_id,
      })
      if (code === 200) {
        item.is_favorite = item.is_favorite === 1 ? 0 : 1
        item.favorite_count += item.is_favorite ? 1 : -1
      }
    },
    // handleCollect(item) {
    //   this.$set(item, 'collects', (item.collects || 0) + 1)
    // },
    handleShare(item) {
      if (!getToken()) {
        this.$message.warning('请先登录再操作！') // 改用 warning 提示更醒目
        return
      }
      this.$set(item, 'shares', (item.shares || 0) + 1)
    },
  },
}
</script>

<style scoped>
.main-container {
  background: rgba(255, 255, 255, 0.1);
}
.vertical-swiper {
  height: 70vh;
}

.vertical-slide {
  width: 100%;
  height: 100%;
  position: relative;
}

.horizontal-swiper {
  width: 100%;
  height: 100%;
  cursor: grab;
}

.horizontal-swiper:active {
  cursor: grabbing;
}

.horizontal-slide {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 图片容器：确保宽高固定 */
.image-container,
.single-image-container {
  width: 40%; /* 与图片宽度一致 */
  height: 100%; /* 与图片高度一致 */
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

/* 图片样式：强制宽高一致（解决大小不一问题） */
.full-image {
  width: 100%; /* 填满容器宽度 */
  height: 100%; /* 填满容器高度 */
  object-fit: cover; /* 保持比例，完整显示 */
  border-radius: 8px;
  transition: opacity 0.3s ease;
  opacity: 0;
  user-select: none;
}

.full-image.loaded {
  opacity: 1;
}

.image-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.horizontal-dots {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  z-index: 10;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s;
}

.dot.active {
  background: #fff;
  width: 24px;
  border-radius: 4px;
}

.left-info {
  /* width: 200px; */
  position: absolute;
  bottom: 20px;
  left: 30px;
  color: white;
  font-size: 14px;
  padding: 8px;
  /* background: rgba(0, 0, 0, 0.5); */
  border-radius: 6px;
  min-width: 260px;
  max-width: 400px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  justify-content: space-around;
  .leftbox {
    /* display: flex; */
    .time {
      margin-top: 10px;
    }
  }
  .lsftbtm {
    line-height: 50px;
  }
}

.right-actions {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  z-index: 5000;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  .collect {
    width: 35px;
    height: 35px;
  }
}

.action-item .count {
  font-size: 10px;
  color: #ccc;
  margin-top: 2px;
}
</style>
